﻿
using Microsoft.AspNetCore.Connections;
using Microsoft.AspNetCore.SignalR.Client;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Text;
using System.Threading.Channels;

HubConnection conn = new HubConnectionBuilder()
    .WithUrl("http://localhost:5109/ServiceHub")
    .Build();

conn.On<string>("ServiceHub", msg =>
{
    Console.Out.WriteLineAsync($"收到了消息:{msg}");
    Console.Out.WriteLineAsync();
});
conn.StartAsync();


void Start()
{
    while (true)
    {
        ReSend:
        Console.Write("请输入需要发送的消息：");
        string ms = Console.ReadLine();
        if (string.IsNullOrEmpty(ms)) { goto ReSend; }
        try
        {
            //conn.InvokeAsync("DDDD", ms);
            conn.SendAsync("DDDD", ms);
        }
        catch (Exception x)
        {
            Console.WriteLine(x);
        }
    }
}

var connectionFactory = new ConnectionFactory();
var connection = await connectionFactory.CreateConnectionAsync();
var channel = await connection.CreateChannelAsync();

var consumer = new AsyncEventingBasicConsumer(channel);
consumer.ReceivedAsync += Consumer_ReceivedAsync;
while (true) { 
await channel.BasicConsumeAsync(queue: "RabbitMQQueue", autoAck: true, consumer: consumer);
}
async Task Consumer_ReceivedAsync(object sender, BasicDeliverEventArgs @event)
{
    await Console.Out.WriteLineAsync(Encoding.UTF8.GetString(@event.Body.ToArray()));
}


//Start();